package cake.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cake.dao.CakeDao;
import cake.dao.CategoryDao;
import cake.dao.impl.CakeDaoImpl;
import cake.dao.impl.CategoryDaoImpl;
import cake.entity.Cake;
import cake.entity.Category;

@WebServlet("/admin/cakelist.html")
public class AdminCakeListServlet extends HttpServlet {
	
	private CakeDao cakeDao=new CakeDaoImpl();
	private CategoryDao categoryDao=new CategoryDaoImpl();

	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		int cid =0;
		int pageNum=1;
		int total=0;
		int pageSize=6;
		String title="";
		
		if (req.getParameter("cid")!=null && !req.getParameter("cid").isEmpty()) {
			cid=Integer.valueOf(req.getParameter("cid"));
		}
		if (req.getParameter("pageNum")!=null && !req.getParameter("pageNum").isEmpty()) {
			pageNum=Integer.valueOf(req.getParameter("pageNum"));
		}
		if(req.getParameter("title")!=null&&!req.getParameter("title").isEmpty()) {
			title = req.getParameter("title");
		}
		
		List<Category> list=categoryDao.getAllCategory();
		req.setAttribute("categories", list);
		List<Cake> cakes=cakeDao.getCakeByCategory(cid,title, pageNum, pageSize);
		req.setAttribute("cakes", cakes);
		
		total=cakeDao.totalCakeByCategoryId(cid,title);
		int totalPage=0;
		totalPage=total%pageSize==0?total/pageSize:total/pageSize+1;
		
		req.setAttribute("totalPage", totalPage);
		req.setAttribute("total", total);
		req.setAttribute("pageNum", pageNum);
		req.setAttribute("cid", cid);
		if(req.getParameter("did")!=null&&!req.getParameter("did").isEmpty()) {
			int did=Integer.parseInt(req.getParameter("did"));
			Cake cake=cakeDao.getCakeById(did);
			if(cake.isCakeStatus()) {
				cake.setCakeStatus(false);
			}else {
				cake.setCakeStatus(true);
			}
			cakeDao.updateCake(cake, did);
			resp.sendRedirect("cakelist.html");
		}else {
			req.getRequestDispatcher("cakelist.jsp").forward(req, resp);
		}
	}
}